<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>留言反馈</strong>
    </h2>
    <div class="setting-operation">
      <SearchCmp v-if="searchCmpArray.length" ref="searchCmpRef" :searchCmpArray="searchCmpArray" :searchForm="queryData"
      @onSubmit="handleSearch" style="margin-bottom: 10px;" />
      <el-badge :value="unReadCount" :hidden="unReadCount === 0">
        <el-button type="primary" plain @click="handleReadAll">全部已读</el-button>
      </el-badge>
    </div>
    <RuifoxTable v-loading="tableLoading" :table-data="tableData" :field-list="fieldList" :default-index="true" :default-checkbox="true">
      <template #default-checkbox="{ element }">
        <div class="table-div-check">
          <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
        </div>
      </template>
      <!-- 推荐图标列 -->
      <template #recommend="{ element }">
        <span :title="element.isRecommend ? '取消推荐' : '推荐'" class="recommend-btn" :class="{'is-recommended': element.isRecommend}" @click="handleRecommend(element)">
          <i class="iconfont">&#xe6f4;</i>
        </span>
      </template>

      <!-- 内容列 -->
      <template #content="{ element }">
        <el-badge value="new" :hidden="element.isRead" style="margin: 10px 20px 0 0;">
          <span class="content-text" @click="showDetail(element)">{{ element.content.comment?.value }}</span>
        </el-badge>
      </template>

      <!-- 创建时间列 -->
      <template #createTime="{ element }">
        {{ dayjs(element.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>

      <!-- 公开状态列 -->
      <template #isOpen="{ element }">
        <el-switch v-model="element.isOpen" :before-change="() => handleOpen(element)" />
      </template>

      <!-- 回复时间列 -->
      <template #replyTime="{ element }">
        {{ element.replyTime ? dayjs(element.replyTime).format('YYYY-MM-DD HH:mm:ss') : '未回复' }}
      </template>

      <!-- 操作列 -->
      <template #options="{ element }">
        <div class="table-td-option unmover">
          <el-button type="primary" size="small" link @click="showDetail(element)">回复</el-button>
          <el-button type="primary" size="small" link @click="handleEdit(element)">编辑</el-button>
          <el-button type="primary" size="small" link @click="handleDelete(element)">删除</el-button>
        </div>
      </template>
    </RuifoxTable>
    <PaginationView :total="queryData.total" :pageSize="queryData.pageSize" :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn" :pageChoose="isPageChooseBtn" :options="batchOptions" :checkedNum="checkedNum"
      :canChoose="queryData.total > 0" @changeSize="handleSizeChange" @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose" @changeAllChoose="handleAllChoose" @invertChoose="handleInvertChoose"
      @checkOption="handleBatchOptions" @refreshList="getTableData" @cancelChoose="handleResetPagination" />

    <!-- 回复 -->
    <el-dialog v-model="replyDialogVisible" title="回复留言" width="1000px">
      <TinymceEditor v-model:modelValue="replyForm.content.comment.value" :minHeight="500" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReplySubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="editDialogVisible" title="修改留言" width="1000px">
      <TinymceEditor v-model:modelValue="editForm.content.comment.value" :minHeight="500" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog v-model="detailDialogVisible" title="留言详情" width="1000px" class="comment-detail-dialog">
      <el-scrollbar height="600px">
        <div class="comment-detail">
          <!-- 留言主体 -->
          <div class="comment-header">
            <div class="header-title">
              <span class="title">网友留言</span>
            </div>
          </div>
          <div class="main-comment">
            <!-- 留言标题栏 -->
            <div class="comment-title">
              <div class="left">
                <span class="label">留言时间：</span>
                <span class="value">{{ dayjs(currentDetail.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
              </div>
              <div class="right">
                <el-tag :type="currentDetail.isOpen ? 'success' : 'warning'" size="small">
                  {{ currentDetail.isOpen ? '已公开' : '未公开' }}
                </el-tag>
                <el-button type="primary" link @click="handleReply(currentDetail)">回复</el-button>
              </div>
            </div>
            <!-- 留言信息 -->
            <div class="comment-info">
              <div class="info-item">
                <span class="label">IP地址：</span>
                <span class="value">{{ currentDetail.ip }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属栏目：</span>
                <span class="value">{{ currentDetail.categoryName }}</span>
              </div>
              <!-- 自定义表单项 -->
              <div v-for="(item, index) in dynamicFields" :key="index" class="info-item">
                <span class="label">{{ currentDetail.content[item].label }}:</span>
                <span class="value">{{ currentDetail.content[item].value }}</span>
              </div>
            </div>
            <!-- 分割线 -->
            <el-divider />
            <!-- 留言内容 -->
            <div class="comment-content" v-html="currentDetail.content.comment.value"></div>
          </div>

          <!-- 回复列表 -->
          <div v-if="currentDetail.children?.length" class="reply-list">
            <div class="reply-header">
              <div class="header-title">
                <span class="title">官方回复</span>
                <span class="count">(共 {{ currentDetail.children?.length }} 条)</span>
              </div>
            </div>
            <div class="reply-items">
              <div v-for="reply in currentDetail.children" :key="reply.id" class="reply-item">
                <div class="reply-info">
                  <div class="left">
                    <span class="username">回复人：{{ reply.username }}</span>
                    <span class="time">回复时间：{{ dayjs(reply.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
                  </div>
                  <div class="right">
                    <div class="reply-actions">
                      <el-button type="primary" link @click="handleEdit(reply)">编辑</el-button>
                      <el-button type="primary" link @click="handleDelete(reply)">删除</el-button>
                    </div>
                  </div>
                </div>
                <el-divider />
                <div class="reply-content" v-html="reply.content.comment.value"></div>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无回复" />
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { selectSelfCommentPage, deleteComment, deleteCommentBatch, insertComment, updateComment, openComment, openCommentBatch, recommendComment, recommendCommentBatch, selectCommentById, readComment, readCommentBatch } from '@/api/comment'
import { ElMessage, ElMessageBox } from "element-plus"
import { tableList as mixTable } from '@ruifox-cms/utils'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import TinymceEditor from '@/components/TinymceEditor.vue'

const store = useStore()
const selfCategory = computed(() => store.state.category.categoryFlat.filter(item => item.hasPermission))
const {
  queryData,
  tableData: oriTableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  isAllSearch,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectSelfCommentPage,
  batchFuncApi: deleteCommentBatch
})
const defaultQueryData = {
  total: 0,
  currentPage: 1,
  pageSize: 20
}
Object.assign(queryData, defaultQueryData)
const tableData = ref([])

watch(oriTableData, () => {
  tableData.value = oriTableData.value.map(comment => {
    if (!comment.content) {
      comment.content = {comment: {value: ''}}
      return comment
    }
    const tempElement = document.createElement('div')
    tempElement.innerHTML = comment.content.comment.value || ''
    comment.content.comment.value = tempElement.textContent || tempElement.innerText
    comment.content.comment.value = comment.content.comment.value.replace(/\s+/g, '')
    return comment
  })
    console.log("tableData.value",tableData.value);
})

// 搜索字段 后续需要加上用户名称搜索
const searchCmpArray = ref([
  { label: '公开状态', key: 'isOpen', form_type: 'select', options: [{ label: '已公开', value: true }, { label: '未公开', value: false }] },
  { label: '回复状态', key: 'isReply', form_type: 'select', options: [{ label: '已回复', value: true }, { label: '未回复', value: false }] },
  { label: '所属栏目', key: 'catId', form_type: 'select', options: [] },
])

// 批量操作
const batchOptions = ref([
  { name: '删除', value: 'delete', icon: '&#xe74b;' },
  { name: '公开', value: 'open', icon: '&#xeb46;' },
  { name: '推荐', value: 'recommend', icon: '&#xe6f4;' }
])
const handleBatchOptions = (data) => {
  if (data === 'delete') {
    handleBatchDelete()
  } else if (data === 'open') {
    handleBatchOpen()
  } else if (data === 'recommend') {
    handleBatchRecommend()
  }
}

// 回复相关
const replyDialogVisible = ref(false)
const replyForm = ref({
  content: {
    comment: {
      value: ''
    }
  },
  pid: null
})

// 处理回复按钮点击
const currentComment = ref({})
const handleReply = (element) => {
  currentComment.value = element
  replyForm.value.pid = element.id
  replyForm.value.replyId = element.id
  replyForm.value.content.comment.value = ''
  replyForm.value.systemId = element.systemId
  replyForm.value.catId = element.catId
  replyDialogVisible.value = true
}

// 修改回复提交处理函数
const handleReplySubmit = async () => {
  if (!replyForm.value.content.comment.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    await insertComment(replyForm.value)
    ElMessage.success('回复成功')
    replyDialogVisible.value = false
    await getTableData()
    // 如果详情弹窗打开，重新获取详情数据
    if (detailDialogVisible.value) {
      await refreshDetailData()
    }
  } catch (error) {
    ElMessage.error('回复失败')
  }
}

// 修改
const editDialogVisible = ref(false)
const editForm = ref({})
const handleEdit = async (data) => {
  try {
    const res = await selectCommentById({ id: data.id })
    if (res.code === 20000) {
      editForm.value = {
        id: data.id,
        content: res.data.content
      }
      editDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取评论详情失败')
  }
}

const handleEditSubmit = async () => {
  if (!editForm.value.content.comment.value.trim()) {
    ElMessage.warning('请输入留言内容')
    return
  }

  try {
    await updateComment(editForm.value)
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    await getTableData()
    // 如果详情弹窗打开，重新获取详情数据
    if (detailDialogVisible.value) {
      await refreshDetailData()
    }
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 删除
const handleDelete = async (data) => {
  ElMessageBox.confirm('是否删除该留言？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteComment({ id: data.id })
    if (res.code === 20000) {
      ElMessage.success('删除成功')
      // 如果删除的是当前详情中的评论，关闭详情弹窗
      if (detailDialogVisible.value && currentDetail.value.id === data.id) {
        detailDialogVisible.value = false
      }
      // 如果删除的是详情中的回复，更新详情数据
      else if (detailDialogVisible.value && data.pid === currentDetail.value.id) {
        await getTableData()
        await refreshDetailData()
      } else {
        await getTableData()
      }
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否批量删除所选留言？</p><span style="font-size: 14px;color: #FF5240;">删除后留言将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteCommentBatch({ ids: checkedList.value, isAllChoose: isAllSearch.value }).then(() => {
      //更新节点
      handleResetPagination()
      getTableData()
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    })
  })
}

// 添加详情相关的数据和方法
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const dynamicFields = ref([])

const showDetail = async (row) => {
  currentDetail.value = row
  dynamicFields.value = Object.keys(row.content)
  dynamicFields.value = dynamicFields.value.filter(item => item !== 'comment')
  detailDialogVisible.value = true
  if (!row.isRead) {
    await readComment({ id: row.id, isRead: true })
    row.isRead = true
    getUnReadCount()
  }
}

// 批量已读
const handleReadAll = () => {
  readCommentBatch({ ids: [], isAllChoose: true, isRead: true }).then(() => {
    ElMessage.success('全部已读')
    getTableData()
    getUnReadCount()
  })
}

// 公开
const handleOpen = async (row) => {
  return new Promise((resolve) => {
    openComment({
      id: row.id,
      isOpen: !row.isOpen
    })
      .then(() => {
        ElMessage.success('状态更新成功')
        // 如果详情弹窗打开且是当前评论，重新获取详情数据
        if (detailDialogVisible.value && currentDetail.value.id === row.id) {
          refreshDetailData()
        }
        resolve(true)
      })
      .catch(() => {
        ElMessage.error('状态更新失败')
        resolve(false)
      })
  })
}

// 批量公开
const handleBatchOpen = () => {
  const data = {
    ids: checkedList.value,
    isAllChoose: isAllSearch.value,
    isOpen: true
  }
  openCommentBatch(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success('状态更新成功')
      getTableData()
      isAllSearch.value = false
      isAllChooseBtn.value = false
      checkedList.value = []
    }
  })
}

const refreshDetailData = async () => {
  try {
    const res = await selectCommentById({ id: currentDetail.value.id })
    if (res.code === 20000) {
      currentDetail.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取评论详情失败')
  }
}

// 推荐
const handleRecommend = async (row) => {
  try {
    await recommendComment({
      id: row.id,
      isRecommend: !row.isRecommend
    })
    ElMessage.success(row.isRecommend ? '取消推荐成功' : '推荐成功')
    getTableData()
  } catch (error) {
    ElMessage.error(row.isRecommend ? '取消推荐失败' : '推荐失败')
  }
}

// 批量推荐
const handleBatchRecommend = () => {
  const data = {
    ids: checkedList.value,
    isAllChoose: isAllSearch.value,
    isRecommend: true
  }
  recommendCommentBatch(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success('状态更新成功')
      getTableData()
      isAllSearch.value = false
      isAllChooseBtn.value = false
      checkedList.value = []
    }
  })
}

// 添加 fieldList 定义
const fieldList = ref([
  {
    title: '推荐',
    name: 'recommend',
    width: 40,
    hideTitle: true
  },
  {
    title: '留言内容（点击查看详情）',
    name: 'content',
    width: 300,
    showTextTip: false
  },
  {
    title: '留言IP',
    name: 'ip'
  },
  {
    title: '留言时间',
    name: 'createTime'
  },
  {
    title: '所属栏目',
    name: 'categoryName'
  },
  {
    title: '是否公开',
    name: 'isOpen',
  },
  {
    title: '回复人',
    name: 'username',
  },
  {
    title: '回复时间',
    name: 'replyTime',
  },
  {
    title: '操作',
    name: 'options',
    width: 150,
    fixed: 'right'
  }
])

// 查询未读数量
const unReadCount = ref(0)
const getUnReadCount = async () => {
  const res = await selectSelfCommentPage({ currentPage: 1, pageSize: 1, isRead: false })
  if (res.code === 20000) {
    unReadCount.value = res.data.total
  }
}

onMounted(() => {
  searchCmpArray.value[2].options = selfCategory.value.map((item) => {
    return {
      label: item.name,
      value: item.id
    }
  })
  getTableData()
  getUnReadCount()
})
</script>
<style scoped lang='scss'>
.inside-comment {
  width: 100%;
  box-sizing: border-box;
  .setting-operation {
    display: flex;
    justify-content: space-between;
  }
}

.recommend-btn i {
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.recommend-btn.is-recommended i {
  color: $mainColor;
}
.content-text {
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;

  &:hover {
    color: $mainColor;
  }
}

:deep(.comment-detail-dialog) {
  .el-dialog__body {
    padding: 0; // 移除默认内边距

    .el-scrollbar {
      padding: 20px; // 将内边距添加到滚动区域
    }
  }
}

.comment-detail {
  .comment-header {
    margin-bottom: 16px;

    .header-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .main-comment {
    padding: 16px;
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    .comment-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .left {
        display: flex;
        align-items: center;

        .label {
          color: #606266;
          margin-right: 8px;
        }

        .value {
          color: #303133;
        }
      }

      .right {
        display: flex;
        align-items: center;
        gap: 16px;
      }
    }

    .comment-info {
      margin: 12px 0;

      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: #606266;
          margin-right: 8px;
          min-width: 70px;
        }

        .value {
          color: #303133;
        }
      }
    }

    .comment-content {
      padding: 12px 0;

      :deep(*) {
        font-size: 14px !important;
        line-height: 1.6;
      }

      :deep(img) {
        max-width: 100%;
        height: auto;
      }
    }
  }

  .reply-list {
    .reply-header {
      margin-bottom: 16px;

      .header-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;

        .count {
          font-size: 14px;
          color: #909399;
          margin-left: 4px;
          font-weight: normal;
        }
      }
    }

    .reply-items {
      .reply-item {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        margin-bottom: 12px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
        background: #fff;
        transition: box-shadow 0.3s ease;

        &:hover {
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.04);
        }

        &:last-child {
          margin-bottom: 0;
        }

        .reply-info {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;

          .left {
            display: flex;
            align-items: center;
            gap: 24px;

            .username {
              color: #303133;
              font-size: 14px;
            }

            .time {
              color: #909399;
              font-size: 14px;
            }
          }
        }

        .el-divider {
          margin: 12px 0;
          border-top: 1px solid #f0f0f0;
        }

        .reply-content {

          :deep(*) {
            font-size: 14px !important;
            line-height: 1.6;
          }

          :deep(img) {
            max-width: 100%;
            height: auto;
          }
        }
      }
    }
  }
}
</style>